<!doctype html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>JS025-顶部栏案例</title>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        background-color: #222;
        color: snow;
    }

    .container {
        height: 80rem;
        margin: 1rem;
        padding: 1rem;
        border: 1px solid snow;
    }

    .fixed-header {
        position: fixed;
        inset: 0 2rem;
        height: 4rem;
        display: flex;
        align-items: center;
        justify-content: center;
        transform: translateY(-100%);
        font-size: 1.5rem;
        border: 1px solid snow;
        background-color: #222;
        transition: 200ms;
    }

    .trigger-box {
        width: 10rem;
        height: 10rem;
        margin-top: 18rem;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 1px solid snow;
        background-color: #333;
    }
</style>
<body>
<div class="fixed-header">顶部栏</div>
<div class="container">
    <div class="trigger-box">Trigger Box</div>
</div>
<script>
    const fixedHeader = document.querySelector('.fixed-header');
    const triggerBox = document.querySelector('.trigger-box');

    window.addEventListener('scroll', function () {
        const top = document.documentElement.scrollTop;
        fixedHeader.style.transform =
            top >= triggerBox.offsetTop ? 'translateY(0)' : 'translateY(-100%)';
    });

</script>
</body>
</html>